<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="到货单号" prop="arriveNumber">
        <el-input
          v-model="queryParams.arriveNumber"
          placeholder="请输入到货单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="申购单号" prop="requisitionForm">
        <el-input
          v-model="queryParams.requisitionForm"
          placeholder="请输入申购单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图纸图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="业务员" prop="salesName">
        <el-input
          v-model="queryParams.salesName"
          placeholder="请输入业务员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="btn">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['outsource:outbound-storage-order:export']"
        >
          数据导出
        </el-button>
      </div>
      <div>
        <el-button type="primary" @click="openTableTitleSet" >表头设置</el-button>
      </div>
    </div>
    <el-table
      v-loading="loading" 
      :data="list" 
      row-key="id" 
      :height="tableHeight" 
      @selection-change="handleSelectionChange"
      show-summary
      :summary-method="getSummaries"
      border
      ref="multipleTableRef"
    >
      <el-table-column align="center" type="selection" :reserve-selection="true" width="60px" fixed="left" />
      <el-table-column label="序号" align="center" type="index" width="60px" fixed="left" />
      <template v-for="item, index in tableTitleList" >
        <el-table-column 
          v-if="item.isTable && item.type !== 'index'"
          :key="index" 
          :min-width="item.width" 
          :label="item.label" 
          :prop="item.field" 
          :align="item.align"
          :type="item.type"
          :header-align="item.headerAlign"
        >
          <template #default="scope">
            <dict-tag :type="item.dictType" :value="scope.row[item.field]" v-if="item.dictType" />
            <div v-else>{{ scope.row[item.field] }}</div>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="left" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm(scope.row.id)"
            v-hasPermi="['outsource:outbound-storage-order:view']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
</template>

<script setup lang="ts" name="OutboundStorageOrder">
import download from '@/utils/download'
import * as OutboundStorageOrderApi from '@/api/outsource/outsourceInAndOutStorage/outboundStorageOrder'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  arriveNumber: null,
  orderNumber: null,
  supplierName: null,
  salesName: null,
  requisitionForm: null,
  productNumber: null,
  partName: null,
  drawingNumber: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const tableTitleList = ref<CrudSchema[]>([]) //表头
const code = 'OutboundStorageOrder'  //表头名
const tableHeight = ref(0)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await OutboundStorageOrderApi.getOutboundStorageOrderPage(queryParams)
    list.value = data.list
    tableTitleList.value = data.labels
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 打开表头设置
const tableTitleSet = ref()
const openTableTitleSet = () => {
  tableTitleSet.value.open(tableTitleList.value, code)
}

// 合计行
const getSummaries = (param) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (['arriveQuantity'].includes(column.property)) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return (parseFloat(prev) + parseFloat(curr)).toFixed(2)
          } else {
            return parseFloat(prev).toFixed(2)
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    }
  })
  return sums
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const { push } = useRouter() // 路由
const openForm = (id: number) => {
  push({
    path:'/outsource/outsource/warehousingOutbound/outboundStorageOrderDetail',
    query: {
      id
    }
  })
}

/** 导出按钮操作 */
const exportRef = ref()
const handleExport = () => {
  exportRef.value.open()
}

// 多选
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 下载
const multipleTableRef = ref()
const downloadFun = async () => {
  const val = exportRef.value.params
  const params = {
    fileName: val.name,
    ids: []
  }
  if (val.range === 'all') {
    params.ids = []
  } else {
    params.ids = multipleSelection.value.map((item) => {
      return item['id']
    })
  }
  const data = await OutboundStorageOrderApi.exportOutboundStorageOrder(params)
  download.excel(data, val.name)
  multipleTableRef.value!.clearSelection()
  multipleSelection.value = []
}

/** 初始化 **/
onMounted(() => {
  const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
  tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 115
  getList()
})
</script>
<style lang="scss" scoped>
.btn {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
